package mo.tags.stack;


import java.util.*;

public class NestedIterator implements Iterator<Integer> {

    private Queue<Integer> queue = new ArrayDeque<>();

    public NestedIterator(List<NestedInteger> nestedList) {
        for (int i = 0; i < nestedList.size(); i++) {
            NestedInteger nestedInteger = nestedList.get(i);
            unbox(nestedInteger);
        }
    }

    private void unbox(NestedInteger nestedInteger) {
        if (nestedInteger.isInteger()) {
            queue.add(nestedInteger.getInteger());
        } else {
            List<NestedInteger> list = nestedInteger.getList();
            for (NestedInteger i : list) {
                unbox(i);
            }
        }
    }

    @Override
    public Integer next() {
        return queue.poll();
    }

    @Override
    public boolean hasNext() {
        return !queue.isEmpty();
    }


    private interface NestedInteger {


        public boolean isInteger();

        public Integer getInteger();

        public List<NestedInteger> getList();

    }

}
